package com.itmk.web.clsases.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itmk.utils.ResultUtils;
import com.itmk.utils.ResultVo;
import com.itmk.web.clsases.entity.ClassParm;
import com.itmk.web.clsases.entity.Clsases;
import com.itmk.web.clsases.service.ClsasesService;
import com.itmk.web.schedule.entity.SelectOption;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Author java实战基地
 * @Version 2383404558
 */
@RestController
@RequestMapping("/api/classes")
public class ClsasesController {
    @Autowired
    private ClsasesService clsasesService;

    //新增
    @PostMapping
    public ResultVo add(@RequestBody Clsases clsases){
        boolean save = clsasesService.save(clsases);
        if(save){
            return ResultUtils.success("新增成功");
        }
        return ResultUtils.error("新增失败!");
    }

    //编辑
    @PutMapping
    public ResultVo edit(@RequestBody Clsases clsases){
        boolean save = clsasesService.updateById(clsases);
        if(save){
            return ResultUtils.success("编辑成功");
        }
        return ResultUtils.error("编辑失败!");
    }

    //删除
    @DeleteMapping("/{classId}")
    public ResultVo delete(@PathVariable("classId") Long classId){
        boolean b = clsasesService.removeById(classId);
        if(b){
            return ResultUtils.success("删除成功");
        }
        return ResultUtils.error("删除失败!");
    }

    //列表
    @GetMapping("/list")
    public ResultVo list(ClassParm parm){
        //构造分页对象
        IPage<Clsases> page = new Page<>(parm.getCurrentPage(),parm.getPageSize());
        //构造查询条件
        QueryWrapper<Clsases> query = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(parm.getClassName())){
            query.lambda().like(Clsases::getClassName,parm.getClassName());
        }
        IPage<Clsases> list = clsasesService.page(page, query);
        return ResultUtils.success("查询成功",list);
    }

    //列表
    @GetMapping("/listClass")
    public ResultVo list(){
        List<Clsases> list = clsasesService.list();
        List<SelectOption> selectOptions = new ArrayList<>();
        Optional.ofNullable(list).orElse(new ArrayList<>())
                .stream()
                .forEach(item -> {
                    SelectOption option = new SelectOption();
                    option.setValue(item.getClassId());
                    option.setLabel(item.getClassName());
                    selectOptions.add(option);
                });
        return ResultUtils.success("查询成功",selectOptions);
    }
}
